#include <stdio.h>
#include "ohos_init.h"
////////修改头文件调用
#include "cmsis_os2.h"

/* 任务ID */
osThreadId_t g_testTaskId;

/* 事件标志ID */
osEventFlagsId_t g_exampleEvent;

/* 等待的事件 */
#define EVENT_WAIT 0x00000001

/* 任务入口函数 */
void Example_Event(void *argument)
{
    uint32_t event;

    /* 等待事件，超时时间为100个时钟节拍，如果在100个时钟节拍内未收到指定事件，任务将被唤醒 */
    printf("Example_Event wait event 0x%x \n", EVENT_WAIT);

    event = osEventFlagsWait(g_exampleEvent, EVENT_WAIT, osFlagsWaitAll, 100);
    if (event == EVENT_WAIT) {
        printf("Example_Event, read event: 0x%x\n", event);
    } else {
        printf("Example_Event, read event timeout\n");
    }
}

uint32_t Example_TaskEntry(void)
{
    osStatus_t ret;
    osThreadAttr_t task1;
    osEventFlagsAttr_t eventAttr = {
        .name = "ExampleEvent",
        .attr_bits = 0U,
        .cb_mem = NULL,
        .cb_size = 0U
    };

    /* 初始化事件标志 */
    g_exampleEvent = osEventFlagsNew(&eventAttr);
    if (g_exampleEvent == NULL) {
        printf("Event flags creation failed.\n");
        return 1;
    }

    /* 设置线程属性 */
    task1.name = "EventTsk1";
    task1.stack_size = 4096;
    task1.priority = osPriorityNormal;
    /* 创建任务 */
    g_testTaskId = osThreadNew(Example_Event, NULL, &task1);

    if (g_testTaskId == NULL) {
        printf("Task creation failed.\n");
        osEventFlagsDelete(g_exampleEvent);
        return 1;
    }

    /* 设置事件标志 */
    printf("Example_TaskEntry write event.\n");
    ret = osEventFlagsSet(g_exampleEvent, EVENT_WAIT);

    if (ret < 0) {
        printf("Event flags set failed.\n");
        osThreadTerminate(g_testTaskId);
        osEventFlagsDelete(g_exampleEvent);
        return 1;
    }

    /* 显示事件标志值 */
    uint32_t flags = osEventFlagsGet(g_exampleEvent);
    printf("EventMask:%lu\n", flags);
    
    /* 清除事件标志 */
    osEventFlagsClear(g_exampleEvent, flags);
    flags = osEventFlagsGet(g_exampleEvent);
    printf("EventMask:%lu\n", flags);

    /* 终止任务 */
    osThreadTerminate(g_testTaskId);

    /* 删除事件标志 */
    osEventFlagsDelete(g_exampleEvent);

    return 0;
}

APP_FEATURE_INIT(Example_TaskEntry); 